const Response = require("../../class/Response");
const LocalEvent = require("../../class/LocalEvent");

// vanilla 功能初始化
/*
    > thisClient.init.vanilla 初始化状态码
    undefined: 未开始初始化
    1: 初始化完成
    2: 未开始初始化
    3: 已初始化1项
    4：已初始化2项
*/

// 客户端连接成功
WSS.on('connection', async (thisClient)=>{
    // 订阅事件
    thisClient.sendJson(
        new Response(Response.MODE.SUBSCRIBE)
        .setEventName("PlayerMessage")
    );

    // 初始化客户端名称、类型
    thisClient.sendJson(
        new Response(Response.MODE.CMD)
        .setCmd("testfor @s")
        .setMetaData({purpose: '/vanilla/init/name'}),
        (req, res)=>{
            init(thisClient);
            thisClient.name = req.body.victim[0];
            thisClient.userType = req.data?.userType ?? 'player';
            thisClient.init.vanilla ++;
            initEnd(thisClient);
            return false;
        }
    );

    // 初始化生成位置
    thisClient.sendJson(
        new Response(Response.MODE.CMD)
        .setCmd("testforblock ~~~ air")
        .setMetaData({purpose: '/vanilla/init/pos'}),
        (req, res)=>{
            init(thisClient);
            thisClient.vanilla.oriPos = req.body.position;
            thisClient.init.vanilla ++;
            initEnd(thisClient);
            return false;
        }
    );
});


function init(thisClient){
    thisClient.init.vanilla ??= 2;
    thisClient.vanilla ??= {
        oriPos: {x:0,y:65,z:0,dimid:0}
    };
}

// 客户端初始化完成
function initEnd(thisClient){
    if (thisClient.init?.vanilla == 4){
        thisClient.init.vanilla = 1;
        WSS.logger.info(`>> 注册Client: ${thisClient.name} | 类型: ${thisClient.userType}`);
        WSS.clientsManager.broadcastLogger(`>> 注册Client: ${thisClient.name} | 类型: ${thisClient.userType}`);
        WSS.clientsManager.broadcastText(`${utils.msgHeader(thisClient.name)} §e已连接: §b${WSS.name}`);
        thisClient.sendText(`${utils.msgHeader(thisClient.name)} §e生成原点: §r${thisClient.vanilla.oriPos.x}, ${thisClient.vanilla.oriPos.y}, ${thisClient.vanilla.oriPos.z}`);
        thisClient.sendText(`${utils.msgHeader(thisClient.name)} §e当前在线: §r${WSS.clientsManager.length}个连接`);
        thisClient.sendText(`${utils.msgHeader(thisClient.name)} §7输入 ./help 查看帮助`);
        return true;
    }

    //  玩家连接 则 广播客户端连接事件
    if (thisClient.userType == 'player'){
        WSS.clientsManager.broadcastJson(new Response()
            .setUrl(CONSTANTS.EVENT.CLIENT_CONNECT)
            .setSourceId(thisClient.id)
            .setData(thisClient.getClientInfo())
        );
        // 本地事件
        WSS.api.listener.emit(CONSTANTS.EVENT.CLIENT_CONNECT, new LocalEvent()
            .setSourceId(thisClient.id)
            .setStatusCode(0)
            .setStatusMessage(``)
            .setData(thisClient.getClientInfo()).json
        );
    }
}